package com.zsl.controller.Login;

import com.alibaba.fastjson.JSON;
import com.zsl.model.Users;
import com.zsl.service.UsersService;
import com.zsl.service.impl.UsersServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@WebServlet(name = "Register", urlPatterns = "/register")
public class Register extends HttpServlet {
    UsersService usersService = new UsersServiceImpl();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        Map<String, Object> res = new HashMap<>();

        //获取数据
        //获取数据
        String uname = request.getParameter("uname").equals("") ? null : request.getParameter("uname");
        String pwd = request.getParameter("pwd").equals("") ? null : request.getParameter("pwd");
        String email = request.getParameter("email").equals("") ? null : request.getParameter("email");
        String cellphone = request.getParameter("cellphone").equals("") ? null : request.getParameter("cellphone");
        String mobilephone = request.getParameter("mobilephone").equals("") ? null : request.getParameter("mobilephone");
        String address = request.getParameter("address").equals("") ? null : request.getParameter("address");

        if (uname == null || pwd == null || email == null) {
            res.put("code", 0);
            res.put("msg", "输出错误");
            out.write(JSON.toJSONString(res));
            return;
        }
        Users user=new Users(
                UUID.randomUUID().toString(),
                uname,
                pwd,
                cellphone,
                mobilephone,
                address,
                email
        );
        res = usersService.addUsers(user);
        if(res.get("code").equals(1)){
            //设置session
            HttpSession session = request.getSession();
            session.setAttribute("role","users");
            session.setAttribute("id",user.getId());
        }
        out.write(JSON.toJSONString(res));
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
